package org.adorsys.aderp.aderplogin.security;

import java.util.List;

import org.adorsys.aderp.aderplogin.client.UserDetailsHelper;
import org.adorsys.aderp.aderplogin.domain.AderpUser;
import org.adorsys.aderp.aderplogin.repository.AderpUserRepository;
import org.adorsys.aderp.jpa.security.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * This local user detail service is not available outside of this module.
 * 
 * Operation provided here are only meaning full for the business logic of this
 * module.
 * 
 * This is also why we will not define any service interface.
 * 
 * @author francis
 * 
 */
@Service
@Transactional
public class LocalUserDetailServiceImpl implements UserDetailsService, PasswordEncoder {

	private static StrongPasswordEncryptor jasyptPasswordEncryptor = new StrongPasswordEncryptor();

	@Autowired
	private AderpUserRepository aderpUserRepository;

	public AderpUser getAderpUser() {
		UserDetails userDetails = SecurityUtils.getUserDetails();
		if (userDetails == null)
			return null;
		String username = userDetails.getUsername();
		List<AderpUser> users = aderpUserRepository.findByUserName(username);
		if (users.isEmpty())
			return null;
		return users.iterator().next();
	}

	public String encryptPassword(String newPassword) {
		return jasyptPasswordEncryptor.encryptPassword(newPassword);
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		try {

			if (StringUtils.isBlank(username)) {
				throw new UsernameNotFoundException(
						"Estate user with email not found");
			}
			
			List<AderpUser> users = aderpUserRepository.findByUserName(username);
			if (users.isEmpty())
				throw new UsernameNotFoundException(
						"User with email not found");
			
			return UserDetailsHelper.createUserDetails(users.iterator().next());
		} finally {

		}
	}

	@Override
	public String encodePassword(String rawPass, Object salt) {
		return jasyptPasswordEncryptor.encryptPassword(rawPass);
	}

	@Override
	public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
		return jasyptPasswordEncryptor.checkPassword(rawPass, encPass);
	}
}
